<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { api } from '@/utils/request'

const show = defineModel<boolean>('modelValue', { required: true })
const rate = ref(0.01)
const feePercent = ref(10)
const minPoints = ref(0)

const form = ref({
  points: 0,
  bankName: '',
  accountName: '',
  accountNumber: '',
  accountId: ''
})
const preview = ref({ gross: 0, fee: 0, net: 0 })

// 禁用复制粘贴的事件处理函数
function preventCopyPaste(event: Event) {
  event.preventDefault()
  event.stopPropagation()
  return false
}

// 禁用右键菜单
function preventContextMenu(event: Event) {
  event.preventDefault()
  event.stopPropagation()
  return false
}

// 禁用键盘快捷键 (Ctrl+C, Ctrl+V, Ctrl+X, Ctrl+A, Cmd+C, Cmd+V, Cmd+X, Cmd+A)
function preventKeyboardShortcuts(event: KeyboardEvent) {
  // 检查 Ctrl (Windows/Android) 或 Cmd (iOS/Mac) 键
  if (event.ctrlKey || event.metaKey) {
    const key = event.key.toLowerCase()
    // 只禁用复制、粘贴、剪切、全选操作
    if (['c', 'v', 'x', 'a'].includes(key)) {
      event.preventDefault()
      event.stopPropagation()
      return false
    }
  }
  return true
}

// 智能检测粘贴操作，允许正常输入和删除
function handleSecureInput(event: Event) {
  const target = event.target as HTMLInputElement
  const inputEvent = event as InputEvent
  
  // 允许删除操作
  if (inputEvent.inputType === 'deleteContentBackward' || 
      inputEvent.inputType === 'deleteContentForward' ||
      inputEvent.inputType === 'deleteWordBackward' ||
      inputEvent.inputType === 'deleteWordForward' ||
      inputEvent.inputType === 'deleteByCut') {
    return true
  }
  
  // 允许正常字符输入
  if (inputEvent.inputType === 'insertText' && inputEvent.data && inputEvent.data.length <= 1) {
    return true
  }
  
  // 阻止粘贴操作 (insertFromPaste, insertFromDrop等)
  if (inputEvent.inputType === 'insertFromPaste' || 
      inputEvent.inputType === 'insertFromDrop' ||
      inputEvent.inputType === 'insertReplacementText' ||
      (inputEvent.data && inputEvent.data.length > 1)) {
    event.preventDefault()
    event.stopPropagation()
    return false
  }
  
  return true
}

async function fetchConfig() {
  try {
    const res = await api.get('/api/pay/withdraw-config')
    const data = await res.json()
    rate.value = Number(data?.rate !== undefined ? data.rate : 0.01)
    feePercent.value = Number(data?.feePercent !== undefined ? data.feePercent : 10)
    minPoints.value = Number(data?.minPoints !== undefined ? data.minPoints : 0)
  } catch (e) {
    console.error('Failed to fetch withdraw config:', e)
  }
}

function recalc() {
  const gross = (form.value.points || 0) * rate.value
  const fee = +(gross * (feePercent.value / 100)).toFixed(2)
  const net = +(gross - fee).toFixed(2)
  preview.value = { gross: +gross.toFixed(2), fee, net }
}

watch(() => form.value.points, recalc)

async function submit() {
  if (!form.value.points || form.value.points <= 0) {
    alert('포인트를 입력하세요')
    return
  }
  if (form.value.points < minPoints.value) {
    alert(`최소 출금 포인트는 ${minPoints.value}입니다`)
    return
  }

  // 验证银行信息
  if (!form.value.bankName.trim()) {
    alert('은행명을 입력하세요')
    return
  }
  if (!form.value.accountName.trim()) {
    alert('계좌 명의를 입력하세요')
    return
  }
  if (!form.value.accountNumber.trim()) {
    alert('은행 계좌번호를 입력하세요')
    return
  }
  if (!form.value.accountId.trim()) {
    alert('신분증 번호를 입력하세요')
    return
  }

  try {
    const res = await api.post('/api/pay/withdrawals', {
      pointsToWithdraw: String(form.value.points),
      bankName: form.value.bankName.trim(),
      accountName: form.value.accountName.trim(),
      accountNumber: form.value.accountNumber.trim(),
      accountId: form.value.accountId.trim(),
    })
    if (res.ok) {
      alert('신청이 제출되었습니다. 관리자 처리를 기다려주세요')
      show.value = false
    } else {
      const err = await res.json().catch(() => ({}))
      alert(err?.error || '제출 실패')
    }
  } catch (e: any) {
    alert(e?.message || '네트워크 오류')
  }
}

function close() {
  show.value = false
}

onMounted(() => {
  fetchConfig()
  recalc()
})
</script>

<template>
  <div v-if="show" class="modal-mask" @click.self="close">
    <div class="modal">
      <div class="modal-header">
        <h3>출금 신청</h3>
        <button class="close" @click="close">✕</button>
      </div>
      <div class="modal-body">
        <div class="section">
          <div class="label">출금 포인트</div>
          <div class="value"><input type="number" v-model.number="form.points" :min="minPoints" /></div>
        </div>

        <div class="hint">
          현재 환율: 1 포인트 = {{ rate }} 화폐 단위; 플랫폼 수수료: {{ feePercent }}%<br>
          최소 출금 포인트: {{ minPoints }}
        </div>

        <!-- 银行信息输入 -->
        <div class="bank-info-section">
          <h4>은행 정보</h4>
          <div class="section">
            <div class="label">은행명</div>
            <div class="value">
              <input
                type="text"
                v-model="form.bankName"
                placeholder="은행명을 입력하세요"
                @paste="preventCopyPaste"
                @copy="preventCopyPaste"
                @cut="preventCopyPaste"
                @contextmenu="preventContextMenu"
                @keydown="preventKeyboardShortcuts"
                @beforeinput="handleSecureInput"
                @drop="preventCopyPaste"
                @dragstart="preventCopyPaste"
                @dragover="preventCopyPaste"
                autocomplete="off"
                spellcheck="false"
              />
            </div>
          </div>
          <div class="section">
            <div class="label">계좌 명의</div>
            <div class="value">
              <input
                type="text"
                v-model="form.accountName"
                placeholder="계좌 명의를 입력하세요"
                @paste="preventCopyPaste"
                @copy="preventCopyPaste"
                @cut="preventCopyPaste"
                @contextmenu="preventContextMenu"
                @keydown="preventKeyboardShortcuts"
                @beforeinput="handleSecureInput"
                @drop="preventCopyPaste"
                @dragstart="preventCopyPaste"
                @dragover="preventCopyPaste"
                autocomplete="off"
                spellcheck="false"
              />
            </div>
          </div>
          <div class="section">
            <div class="label">은행 계좌번호</div>
            <div class="value">
              <input
                type="text"
                v-model="form.accountNumber"
                placeholder="은행 계좌번호를 입력하세요"
                @paste="preventCopyPaste"
                @copy="preventCopyPaste"
                @cut="preventCopyPaste"
                @contextmenu="preventContextMenu"
                @keydown="preventKeyboardShortcuts"
                @beforeinput="handleSecureInput"
                @drop="preventCopyPaste"
                @dragstart="preventCopyPaste"
                @dragover="preventCopyPaste"
                autocomplete="off"
                spellcheck="false"
              />
            </div>
          </div>
          <div class="section">
            <div class="label">신분증 번호</div>
            <div class="value">
              <input
                type="text"
                v-model="form.accountId"
                placeholder="신분증 번호를 입력하세요"
                @paste="preventCopyPaste"
                @copy="preventCopyPaste"
                @cut="preventCopyPaste"
                @contextmenu="preventContextMenu"
                @keydown="preventKeyboardShortcuts"
                @beforeinput="handleSecureInput"
                @drop="preventCopyPaste"
                @dragstart="preventCopyPaste"
                @dragover="preventCopyPaste"
                autocomplete="off"
                spellcheck="false"
              />
            </div>
          </div>
        </div>
        <div class="section">
          <div class="label">예상 입금액</div>
          <div class="value emphasis">{{ preview.net.toFixed(2) }}</div>
        </div>

        <div class="notice">
          <p>★환전안내★ : 환전신청은 다이아 등급 회원부터 가능합니다.</p>
          <p>첫환전시 수수료 무료( 두번째 환전부터 수수료 25% 발생)</p>
          <p>타인의 출금방지를 위해서 1명의1회출금신청 가능합니다</p>
          <p>퀵환전은 환전시간 딜레이없이 당일 바로 환전 가능합니다</p>
        </div>
      </div>
      <div class="modal-footer">
        <button class="primary" @click="submit">신청 제출</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.modal-mask {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.modal {
  width: min(520px, 90vw);
  max-height: 80vh;
  background: var(--color-bg);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-xl);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: var(--shadow-xl);
  color: var(--color-text);
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--space-4) var(--space-5);
  border-bottom: 1px solid var(--color-border);
  background: var(--color-surface);
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 700;
  color: var(--color-text);
}

.close {
  background: transparent;
  border: 0;
  color: var(--color-text-muted);
  cursor: pointer;
  padding: var(--space-2);
  border-radius: var(--radius-sm);
  font-size: 18px;
  transition: all 0.2s ease;
}

.close:hover {
  background: var(--color-surface-hover);
  color: var(--color-text);
}

.modal-body {
  padding: var(--space-5);
  overflow: auto;
}

.section {
  display: flex;
  align-items: center;
  gap: var(--space-4);
  padding: var(--space-3) 0;
  border-bottom: 1px solid var(--color-border-light);
}

.section:last-of-type {
  border-bottom: none;
}

.label {
  min-width: 100px;
  color: var(--color-text-secondary);
  font-weight: 500;
  text-align: right;
}

.value {
  flex: 1;
}

.value input {
  width: 100%;
  padding: var(--space-2) var(--space-3);
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  color: var(--color-text);
  font-size: 14px;
  transition: all 0.2s ease;
}

.value input:focus {
  outline: none;
  border-color: var(--color-primary);
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.value.emphasis {
  color: var(--color-warning);
  font-weight: 700;
  font-size: 18px;
}

.hint {
  margin-top: var(--space-4);
  padding: var(--space-3);
  background: var(--color-primary-light);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  color: var(--color-primary);
  font-size: 12px;
  line-height: 1.5;
}

.notice {
  margin-top: var(--space-4);
  padding: var(--space-4);
  background: rgba(59, 130, 246, 0.05);
  border: 1px solid rgba(59, 130, 246, 0.2);
  border-radius: var(--radius-lg);
  font-size: 13px;
  color: var(--color-text-secondary);
}

.notice p {
  margin: 0 0 var(--space-2) 0;
  font-weight: 600;
  color: var(--color-primary);
}

.notice ul {
  margin: 0;
  padding-left: var(--space-4);
}

.notice li {
  margin-bottom: var(--space-1);
  line-height: 1.5;
}

.bank-info-section {
  margin-top: var(--space-4);
  padding: var(--space-4);
  background: rgba(99, 102, 241, 0.03);
  border: 1px solid rgba(99, 102, 241, 0.1);
  border-radius: var(--radius-lg);
}

.bank-info-section h4 {
  margin: 0 0 var(--space-3) 0;
  color: var(--color-primary);
  font-size: 14px;
  font-weight: 600;
}

.modal-footer {
  padding: var(--space-4) var(--space-5);
  border-top: 1px solid var(--color-border);
  background: var(--color-surface);
  display: flex;
  justify-content: flex-end;
  gap: var(--space-3);
}

.modal-footer button {
  padding: var(--space-2) var(--space-4);
  border-radius: var(--radius-md);
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.modal-footer button.primary {
  background: var(--color-primary);
  border: 1px solid var(--color-primary);
  color: var(--color-text-white);
}

.modal-footer button.primary:hover {
  background: var(--color-primary-dark);
  border-color: var(--color-primary-dark);
  box-shadow: var(--shadow-md);
}
</style>
